package org.ch04.test00.demo02;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @author CSY
 * @date 2025 - 03 - 28
 */
public class Sum {
    /**
     * 实现计算1到n的和 - 注解设置n上限
     * @param n
     * @return
     */
    public int getSum(@LimitAnnotation(100) int n){
        try {
            Class<Sum> clazz = Sum.class;
            checkLimit(n, clazz,int.class);
            int sum = 0;
            for (int i = 1;i <= n;i++){
                sum += i;
            }
            return sum;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private static void checkLimit(int n, Class<Sum> clazz,Class<?>...param) throws Exception {
        Method method = clazz.getDeclaredMethod("getSum",param);
        Parameter[] parameters = method.getParameters();
        int limit = 0;
        for (Parameter parameter : parameters) {
            if (!parameter.isAnnotationPresent(LimitAnnotation.class)){
                break;
            }
            LimitAnnotation annotation = parameter.getAnnotation(LimitAnnotation.class);
            limit = annotation.value();
        }
        if(limit != 0 && n > limit){
            throw new Exception(n +"超出了指定的上限:"+limit);
        }
    }
}
